#@PydevCodeAnalysisIgnore

from google.appengine.api import memcache
from google.appengine.ext import db
from urllib2 import URLError
from xml.dom import minidom
import jinja2
import logging
import os
import urllib2
import webapp2

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        t = jinja_environment.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

GMAPS_URL = "http://maps.googleapis.com/maps/api/staticmap?size=380x263&sensor=false&"
def gmaps_img(points):
    markers = '&'.join('markers=%s,%s' % (p.lat, p.lon) for p in points)
    return GMAPS_URL + markers

IP_URL = "http://api.hostip.info/?ip="
def get_coords(ip):
    url = IP_URL + ip
    content = None
    try:
        content = urllib2.urlopen(url).read()
    except URLError:
        return
    
    if content:
        d = minidom.parseString(content)
        coords = d.getElementsByTagName("gml:coordinates")
        if coords and coords[0].childNodes[0].nodeValue:
            lon, lat = coords[0].childNodes[0].nodeValue.split(',')
            return db.GeoPt(lat, lon)


class Art(db.Model):
    title = db.StringProperty(required=True)
    art = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    coords = db.GeoPtProperty(required=False)

def top_arts(update=False):
    key = 'top'
    arts = memcache.get('key')
    
    if arts is None or update:
        logging.debug("DB Query")
        arts = db.GqlQuery("select * from Art order by created desc")
        # prevent running multiple queries
        arts = list(arts)
        memcache.set(key, arts)
    return arts

class MainHandler(Handler):
    def render_front(self, title="", art="", error=""):
        arts = top_arts()
        points = filter(None, (a.coords for a in arts))
        img_url = None
        if points:
            img_url = gmaps_img(points)
        
        self.render("front.html", title=title, art=art, error=error, arts=arts, img_url=img_url)

    def get(self):
        return self.render_front()

    def post(self):
        title = self.request.get("title")
        art = self.request.get("art")

        if title and art:
            a = Art(title=title, art=art)
            coords = get_coords(self.request.remote_addr)
            if coords:
                a.coords = coords
            a.put()
            top_arts(True)
            self.redirect("/")
        else:
            error = "We need both title and some artwork!"
            self.render_front(title, art, error)

app = webapp2.WSGIApplication([('/', MainHandler)],
                              debug=True)
